package com.minelx.datamicroscope.querylanguage.data;

import com.minelx.datamicroscope.querylanguage.common.ComboMap;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toList;

public class CollectingMapping {

	private final List<CollectingKey> orderList;

	private final ComboMap<CollectingKey, CollectingField> collectingMapping;

	public CollectingMapping() {
		orderList = new ArrayList<>();
		collectingMapping = new ComboMap<>();
	}

	void put(CollectingKey collectingKey, CollectingField collectingField) {
		put0(requireNonNull(collectingKey), requireNonNull(collectingField));
	}

	private void put0(CollectingKey collectingKey, CollectingField collectingField) {
		// mark order
		if (!orderList.contains(collectingKey)) {
			orderList.add(collectingKey);
		}
		collectingMapping.add(collectingKey, collectingField);
	}

	List<CollectingGroup> groups() {
		List<CollectingGroup> result = new ArrayList<>();
		for (int at = 0; at < orderList.size(); at++) {
			CollectingKey collectingKey = orderList.get(at);
			result.add(CollectingGroup.create("resource" + at,
					collectingKey,
					collectingMapping.get(collectingKey)));
		}
		return result;
	}

	List<CollectingField> values() {
		return collectingMapping.values().stream()
				.flatMap(Collection::stream)
				.collect(toList());
	}
}
